package com.example.api.mall.controller;

import com.example.api.mall.logic.IFileLogic;
import com.example.common.core.annotation.NoLoginAuth;
import com.example.common.core.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private IFileLogic fileLogic;

    /**
     * 上传文件的参数名为：file
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file){
        String url = fileLogic.upload(file);
        return Result.success(url);
    }

    /**
     * 上传多个文件
     * @param files
     * @return
     */
    @PostMapping("/uploads")
    public Result<List<String>> uploads(@RequestParam("file") MultipartFile[] files){
        List<String> urlList = fileLogic.uploads(files);
        return Result.success(urlList);
    }

    /**
     * 上传MultipartFile文件
     * @param file
     * @return
     */
    @NoLoginAuth
    @PostMapping("/uploadToMinio")
    public String uploadToMinio(@RequestParam("file") MultipartFile file) throws Exception {
        String url = fileLogic.uploadToMinio(file);
        return url;
    }

    /**
     * 上传Base64图片
     * @param base64
     */
    @PostMapping("/uploadBase64")
    public String upload2(String base64) throws IOException {
        String url = "/temp/test.jpg";
        final File tempFile = new File(url); // TODO BASE64 方式的 格式和名字需要自己控制（如 png 图片编码后前缀就会是 data:image/png;base64,）
        String[] d = base64.split("base64,");// TODO 防止有的传了 data:image/png;base64, 有的没传的情况
        final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
        FileCopyUtils.copy(bytes, tempFile);
        return url;
    }
}
